import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:znmm/UI/A_Common/video_player_mag.dart';

// String longVideo =
//     "https://www.pintreel.com/wp-content/video/mainvVdeo/4.21FB%E6%B6%A8%E7%B2%89%E6%8A%80%E5%B7%A7.mp4";
String longVideo = "https://media.w3.org/2010/05/sintel/trailer.mp4";

class VideoView extends StatefulWidget {
  final String? videoUrl;

  const VideoView({super.key, this.videoUrl});

  @override
  State<VideoView> createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  late VideoPlayerController? _controller;
  bool _isPlaying = true;
  bool _isFullScreen = false;

  bool _bIsOverlayEntry = false;

  @override
  void initState() {
    super.initState();

    // 获取单例实例并初始化控制器

    VideoPlayerSingleton.instance.initializeController(
      widget.videoUrl,
      callback: () {
        if (mounted) {
          setState(() {});
        }
      },
    );
    _controller = VideoPlayerSingleton.instance.controller;

    // _controller = VideoPlayerController.networkUrl(
    //     Uri.parse(widget.videoUrl ?? longVideo))
    //   ..initialize().then((value) {
    //     _controller.play();

    //     if (mounted) {
    //       setState(() {});
    //     }
    //   });
  }

  @override
  void dispose() {
    // _controller.pause();
    // _controller.dispose();
    //overlayEntry?.remove();

    // 销毁控制器
    if (!_bIsOverlayEntry) {
      VideoPlayerSingleton.instance.disposeController();
    }

    print("***************dispose***************");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
          // if (_isFullScreen) {
          //   // 如果当前处于全屏模式，切换为非全屏
          //   _toggleFullScreen();
          //   return false; // 阻止返回
          // }
          // return true; // 允许返回
        },
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Container(
              color: Colors.black,
              child: Center(
                child: _controller!.value.isInitialized
                    ? AspectRatio(
                        aspectRatio: _controller!.value.aspectRatio, // 16:9
                        child: Stack(
                          alignment: Alignment.bottomCenter,
                          children: [
                            VideoPlayer(_controller!),
                            _buildControls(),
                          ],
                        ),
                      )
                    : const Center(
                        child: CircularProgressIndicator(),
                      )
                // const Text(
                //     "加载中...",
                //     style: TextStyle(fontSize: 21, color: Colors.blue),
                //   )
                ,
              ),
            ),
            if (!_isFullScreen)
              Positioned(
                top: 66.0,
                left: 16.0,
                child: IconButton(
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  color: Colors.white,
                ),
              ),
          ],
        ));
  }

  Widget _buildControls() {
    return Container(
      color: Colors.black.withOpacity(0.2),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
                onPressed: _togglePlayPause,
                color: Colors.white,
              ),
              VideoTimeText(videoPlayerClr: _controller!),
              const Spacer(),
              Text(
                _formatDuration(_controller!.value.duration),
                style:
                    const TextStyle(color: Color.fromRGBO(255, 255, 255, 0.5)),
              ),
              IconButton(
                icon: Icon(
                    _isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen),
                onPressed: _toggleFullScreen,
                color: Colors.white,
              ),
              // 新增的返回按钮
              IconButton(
                icon: const Icon(Icons.arrow_back, color: Colors.white),
                onPressed: () {
                  VideoPlayerSingleton.instance.showFloatingVideo(context);
                  _bIsOverlayEntry = true;
                  // 返回上一层并悬浮视频
                  Navigator.of(context).pop(); // 返回上一层
                  //_showFloatingVideo(context); // 显示悬浮视频
                },
              ),
            ],
          ),
          VideoProgressIndicator(
            _controller!,
            allowScrubbing: true,
            colors: VideoProgressColors(
              playedColor: Colors.red,
              bufferedColor: Colors.white,
              backgroundColor: Colors.white.withOpacity(0.2),
            ),
          ),
        ],
      ),
    );
  }

  void _togglePlayPause() {
    if (mounted) {
      setState(() {
        if (_isPlaying) {
          _controller!.pause();
        } else {
          _controller!.play();
        }
        _isPlaying = !_isPlaying;
      });
    }
  }

  void _toggleFullScreen() {
    if (mounted) {
      setState(() {
        _isFullScreen = !_isFullScreen;
        if (_isFullScreen) {
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeLeft,
            DeviceOrientation.landscapeRight,
          ]);
        } else {
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.portraitUp,
            DeviceOrientation.portraitDown,
          ]);
        }
      });
    }
  }

  String _formatDuration(Duration duration) {
    final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
    final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
    return "$minutes:$seconds";
  }
}

//******************************videoTiem
class VideoTimeText extends StatefulWidget {
  final VideoPlayerController videoPlayerClr;

  const VideoTimeText({super.key, required this.videoPlayerClr});

  @override
  State<VideoTimeText> createState() => _VideoTimeTextState();
}

class _VideoTimeTextState extends State<VideoTimeText> {
  late Duration currentPosition;

  @override
  void initState() {
    super.initState();

    // 添加监听器以在播放器状态更改时更新时间
    widget.videoPlayerClr.addListener(_updateTime);

    // 初始化时间
    currentPosition = widget.videoPlayerClr.value.position;
  }

  @override
  void dispose() {
    widget.videoPlayerClr.removeListener(_updateTime);
    super.dispose();
  }

  void _updateTime() {
    if (mounted) {
      setState(() {
        currentPosition = widget.videoPlayerClr.value.position;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _formatDuration(currentPosition),
      style: const TextStyle(color: Color.fromRGBO(255, 255, 255, 0.5)),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return '$n';
      return '0$n';
    }

    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);
    return '${twoDigits(minutes)}:${twoDigits(seconds)}';
  }
}



/*

    Navigator.push(context, MaterialPageRoute(builder: (context) {
                  // return MyVideo(
                  //   videoUrl: model.url,
                  // );
                  return PTVideoView(
                    videoUrl: model.url,
                  );
                }));

*/